Build A Data Pipeline

What is a data pipeline and why use one?


  • A data pipeline is a repeatable workflow that ingests source data, transforms it, and publishes datasets for analytics, dashboards or machine learning.
  • Inputs may be CSV, JSON, Parquet, databases, logs or event streams. Transformations include parsing, cleaning, joining, deduplicating and aggregating.
  • Pipelines replace manual notebook reruns with scheduled, triggered or continuous processing, reducing missed steps and keeping outputs fresher.
  • Orchestration controls execution order, dependencies, retries and monitoring. A DAG (directed acyclic graph) visualizes which datasets or tasks depend on others.
  • Lakeflow Jobs orchestrate tasks such as notebooks; Lakeflow Spark Declarative Pipelines define datasets and their transformations so Databricks can plan dependencies and updates.

What is the Medallion Architecture?


  • Bronze (raw): Ingest source data with minimal modification so it can be audited or reprocessed. For a bike rental company, this might contain raw rides, customers and maintenance files.
  • Silver (validated): Parse and standardize fields, deduplicate records, handle invalid values, join related data and enforce data-quality expectations.
  • Gold (business-ready): Publish metrics or aggregations such as daily rentals, revenue by region and maintenance trends, typically consumed by BI tools or ML workflows.
  • The normal flow is sources → Bronze → Silver → Gold → dashboards/models. Keeping stages separate helps debugging, lineage and reprocessing.
  • The layers are a design pattern, not three mandatory Databricks object types; implementations may use streaming tables, materialized views or ordinary Delta tables.

What are declarative pipelines and how do they work?


  • A declarative pipeline describes the desired datasets and the queries that produce them; Databricks constructs the dependency DAG and manages execution.
  • Streaming tables incrementally process incoming records, often using Auto Loader for newly arrived files.
  • Materialized views store query results and refresh them from their sources; Databricks may perform incremental refresh when supported, but some queries require full recomputation.
  • Expectations (CONSTRAINT ... EXPECT) measure data quality. Depending on the configured action, invalid rows may be retained, dropped or cause a failed update.
  • Automatic dependency ordering does not eliminate the need to configure pipeline schedules, access permissions, schema handling, recovery and monitoring.

How do you install and explore the bike rental demo?


  • In a new Databricks notebook, run the following setup to install the demo helper and generate the synthetic bike rental project:
%pip install dbdemos -U
import dbdemos
dbdemos.install('pipeline-bike', catalog='main', schema='dbdemos_pipeline_bike')
  • Confirm that you have permission to create objects in the target catalog and schema. The demo package and workspace capabilities may vary by edition.
  • Open the created pipeline project and inspect its Asset browser (source files), Editor (SQL/Python), DAG (dependencies), and Table insights/Inspector (schema, preview and execution details).
  • Explore the source files in a volume. The demo includes daily Parquet, CSV and JSON files for rides, maintenance and customers.
  • Check parsing options when data contains embedded newlines; for supported CSV/JSON reads, multiLine = true can help parse records spanning multiple lines. Validate the output rather than assuming the option fixes malformed source files.
  • Use exploratory notebooks for ad-hoc checks, and keep reusable transformation definitions in pipeline source files.

How do you build Bronze, Silver and Gold datasets with SQL?


  • The following is an illustrative pattern: replace the volume path and column names with those in your environment. In a SQL declarative pipeline, define a Bronze streaming table from newly arriving CSV files:
CREATE OR REFRESH STREAMING TABLE rides_bronze
AS SELECT *
FROM STREAM read_files(
  '/Volumes/main/dbdemos_pipeline_bike/raw/rides/',
  format => 'csv',
  header => true
);
  • STREAM read_files(...) uses Auto Loader semantics for incremental file ingestion. Configure schema inference/evolution and parsing options appropriately for production data.
  • Create a cleaned Silver dataset and a quality rule; ON VIOLATION DROP ROW removes records that fail the expectation:
CREATE OR REFRESH MATERIALIZED VIEW rides_silver (
  CONSTRAINT valid_ride_id EXPECT (ride_id IS NOT NULL)
  ON VIOLATION DROP ROW
)
AS SELECT DISTINCT ride_id, customer_id, ride_date, fare
FROM rides_bronze;
  • Aggregate a Gold dataset for reporting:
CREATE OR REFRESH MATERIALIZED VIEW daily_revenue
AS SELECT ride_date, COUNT(*) AS rides, SUM(fare) AS revenue
FROM rides_silver
GROUP BY ride_date;
  • Run the pipeline, inspect its DAG and preview each output. The exact SQL depends on the source schema and pipeline capabilities; Silver may instead be implemented as a streaming table for incremental processing.

How do you use the Lakeflow Pipeline Editor?


  • Open Jobs & Pipelines, create or open an ETL pipeline, and configure the source files, destination catalog/schema and compute mode.
  • Asset browser (left): Find pipeline SQL/Python files, exploration notebooks, tests and documentation.
  • File editor (centre): Write or modify a dataset definition; use focused runs or validations where available.
  • Pipeline toolbar (top): Open settings and start a pipeline update.
  • Pipeline graph (right): Inspect dataset dependencies, status and execution order.
  • Table insights (bottom): Examine schema, sample rows, data quality metrics, errors and run details.
  • Pipeline updates run dependent transformations in the correct order; review failures at the affected dataset rather than rerunning everything blindly.

How do you build the flight ingestion example in Python?


  • In pipeline Settings → Environment, add the pyspark-data-sources dependency, assuming the package and external OpenSky API are accessible. This is separate from installing packages interactively in a notebook.
  • Create ingest_flights.py to register the external source and declare a streaming table:
from pyspark import pipelines as dp
from pyspark_datasources import OpenSkyDataSource

spark.dataSource.register(OpenSkyDataSource)

@dp.table
def ingest_flights():
    return spark.readStream.format('opensky').load()
  • Create flights_stats.py to define aggregate statistics:
from pyspark import pipelines as dp
from pyspark.sql.functions import count, countDistinct, max

@dp.materialized_view
def flights_stats():
    return spark.read.table('ingest_flights').agg(
        count('*').alias('num_events'),
        countDistinct('icao24').alias('distinct_aircraft'),
        max('velocity').alias('max_velocity')
    )
  • The source demo uses @dp.table for both steps; using @dp.materialized_view for the aggregate makes its batch-style summary intent explicit. Verify the package’s API, source availability and table schema before running.
  • The first definition ingests flight events; the second computes total events, distinct aircraft and maximum observed velocity. The DAG should show ingest_flights → flights_stats.
  • Start the pipeline update, inspect the table previews and any errors, then add further transformations or connect a dashboard to the results.

How do you monitor and troubleshoot a pipeline?


  • Inspect the DAG to locate the first failed dataset, then read its execution logs and error message.
  • Compare Bronze and Silver row counts; expectation metrics can reveal how many rows were rejected or dropped.
  • Validate file parsing and schema inference, especially for multiline CSV/JSON, unexpected columns and missing values.
  • Check catalog/schema permissions, volume paths, SQL warehouse or pipeline compute settings, and external network/API access.
  • Inspect Unity Catalog lineage to understand upstream sources and downstream dashboards; use run history to track refreshes and failures.
  • Refresh schedules and file-arrival triggers must be configured explicitly. A pipeline does not guarantee continuously current data unless its update mode and trigger match the business requirement.

Where can you read more?